package com.simpou.commons.web.filter;

import lombok.AllArgsConstructor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Filtro para permitir requisições CORS. Ecoa as opções da requisição para a
 * resposta de forma a permitirem todas as chamadas.
 *
 * @author Jonas Pereira
 * @since 2013-01-14
 */
public class CORSFilter extends AbstractCORSFilter implements Filter {
    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(final ServletRequest request,
        final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final HeaderImpl responseImpl = new HeaderImpl(httpRequest,
                (HttpServletResponse) response);
        final String method = httpRequest.getMethod();

        if (method.equals("OPTIONS")) {
            super.fillHeader(responseImpl, method);
        } else {
            super.fillHeader(responseImpl, method);
            chain.doFilter(request, response);
        }
    }

    @AllArgsConstructor
    private static class HeaderImpl implements AbstractCORSFilter.Header {
        private final HttpServletRequest request;
        private final HttpServletResponse response;

        @Override
        public void addResponseHeader(final String key, final String value) {
            this.response.addHeader(key, value);
        }

        @Override
        public String getRequestHeader(final String key) {
            return this.request.getHeader(key);
        }
    }
}
